package org.bookie.model.services.impl;

import java.util.List;

import org.bookie.model.BetSlip;
import org.bookie.model.Period;
import org.bookie.model.User;
import org.bookie.model.services.BetSlipDAO;
import org.hibernate.Criteria;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 * Hibernate implemetnation of the {@link BetSlipDAO}
 * 
 * @author zubairov
 */
public class HibernateBetSlipDAO extends GenericHibernateDAO<BetSlip, Long> implements BetSlipDAO {

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public List<BetSlip> findByUser(User user, Period period) {
		Criteria criteria = getSession().createCriteria(getPersistentClass());
		addPeriodCriteria("date", criteria, period);
		criteria.add(Restrictions.eq("user", user))
			.addOrder(Order.desc("date"));
		return criteria.list();
	}
	
	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public List<BetSlip> findByUserId(Long id){
		return getSession().createCriteria(getPersistentClass())
				.add(Restrictions.eq("user.id", id))
				.addOrder(Order.asc("date")).list();
	}

	@Override
	public BetSlip makePersistent(BetSlip betSlip) {
		Transaction tx = null;
		try{
			tx = getSession().beginTransaction();
			User user = betSlip.getUser();
			getSession().update(user);
			getSession().save(betSlip);
			user.getAccount().withdraw(betSlip);
			tx.commit();
		}catch (RuntimeException e) {
			tx.rollback();
			throw e;
		}
		return betSlip;
	}

}
